﻿package {
	import laya.webgl.WebGL;
	import laya.net.Loader;
	import laya.utils.Handler;
	import ui.GameStartUI;
	import laya.display.Stage;
	import laya.events.Event;
	import laya.display.Sprite;

	import GameMap;
	import ui.GamePlayUI;
	import ui.GameOverUI;
	import view.GameStart;
	import Role;

	import laya.debug.DebugPanel;
	import laya.ui.Label;

	public class Main { 
		
		private var map:GameMap = null;
		private var play:GamePlay = null;
		private var over:GameOver = null;
		private var start:GameStart = null;

		private var hp:int = 10;
		private var level:int = 1;
		private var score:int = 0;

		private var roleLayer:Sprite;
		private var hero:Role;

		private var moveX:Number;
		private var moveY:Number;

		public function Main() {
			//初始化引擎
			Laya.init(720, 1280, WebGL);
			DebugPanel.init();

			//适配方式（不加这一句的结果是画面会随浏览器的窗口变小而被裁减）
			Laya.stage.scaleMode = Stage.SCALE_SHOWALL;
			
			//真正使用东西前我们需要把资源加载完
			Laya.loader.load("res/atlas/gameUI.atlas", Handler.create(this, this.gameStart));
		}

		private function gameStart(): void {
			start = new GameStart();

			start.btn_start.on(Event.MOUSE_UP, this, gameInit);

			start.popup();
		}

		private function gameInit(): void {

			start.close();

			map = new GameMap();
			Laya.stage.addChild(map);

			play = new GamePlay();
			Laya.stage.addChild(play);

			roleLayer = new Sprite();
			Laya.stage.addChild(roleLayer);

			hero = new Role();
			hero.init("hero", 10, 0);
			hero.pos(360, 800);
			roleLayer.addChild(hero);

			//3秒模拟战斗时间
			// Laya.timer.once(3000, this, gameOver);

			Laya.timer.frameLoop(1, this, loop);
			Laya.stage.on(Event.MOUSE_DOWN, this, onMouseDown);
			Laya.stage.on(Event.MOUSE_UP, this, onMouseUp);
		}

		private function loop(): void {
			map.updateMap();
			play.update(hp, level, score);
			hero.update();
		}

		private function gameOver(): void {
			map.removeSelf();
			play.removeSelf();

			over = new GameOver();
			over.txt_score.text = score.toString();
			over.popup();
			over.on("restart", this, gameInit);

			roleLayer.removeChildren(0, roleLayer.numChildren - 1);
			roleLayer.removeSelf();

			Laya.stage.offAll();
		}

		private function onMouseDown():void {
			moveX = Laya.stage.mouseX;
			moveY = Laya.stage.mouseY;

			Laya.stage.on(Event.MOUSE_MOVE, this, onMouseMove);
		}

		private function onMouseUp():void {
			Laya.stage.off(Event.MOUSE_MOVE, this, onMouseMove);
		}

		private function onMouseMove():void {
			//计算角色移动量(上一帧的位置—当前移动到的位置)
            var xx:Number=moveX-Laya.stage.mouseX;
            var yy:Number=moveY-Laya.stage.mouseY;
            //更新移动位置
            hero.x-=xx;
            hero.y-=yy;
            //更新前一帧位置的座标
            moveX=Laya.stage.mouseX;
            moveY=Laya.stage.mouseY;
		}
	}
}